package com.spice.service.config;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author yhm
 * shiro配置文件
 */
@Configuration
public class ShiroConfig {
    private static final String LOGIN_URL = "/noPermission";
    private static final String UNAUTHORIZED_URL = "/noPermission";

    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(securityManager);
        /*添加shiro内置过滤器
            anon：无需认证
            authc：必须认证
            user：必须拥有 记住我
            perms：拥有对某个资源的权限才能访问
            role：拥有某个角色权限才能访问
        * */
        Map<String, String> filterMap = new LinkedHashMap<String, String>();
//        filterMap.put("/api/helloWorld/**","authc");
//        filterMap.put("/api/login/**","anon");
//        filterMap.put("/api/register/**","anon");
//        filterMap.put("/api/SMS/**","anon");
//        filterMap.put("/**","anon");
//不使用过滤器

        bean.setFilterChainDefinitionMap(filterMap);
        bean.setLoginUrl(LOGIN_URL);
        bean.setUnauthorizedUrl(UNAUTHORIZED_URL);

        return bean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("shiroRealm") ShiroRealm shiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联EnterpriseRealm
        securityManager.setSessionManager(sessionManager());
        securityManager.setRealm(shiroRealm);
        return securityManager;
    }

    @Bean(name = "shiroRealm")
    public ShiroRealm shiroRealm() {
        return new ShiroRealm();
    }

    //自定义sessionManager
    @Bean("sessionManager")
    public DefaultWebSessionManager sessionManager() {
        ShiroSessionManager shiroSessionManager = new ShiroSessionManager();
        return shiroSessionManager;
    }


}





